<template>
  <el-card>
    <el-row type="flex" justify="space-between" style="margin-bottom: 10px">
      <el-col>
        <el-button size="small" @click="handleBack">返回上一页</el-button>
        <span style="font-weight: bold; margin-left: 10px">{{ title }}</span>
      </el-col>
      <div>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-row>
    <el-form :model="formModel" label-width="150px" :rules="rules" ref="form">
      <el-card style="margin-bottom: 10px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="name">
              <el-input
                style="width: 150px"
                v-model="formModel.name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商简称" prop="abName">
              <el-input
                style="width: 150px"
                v-model="formModel.abName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="统一社会信用代码" prop="socialCreditCode">
              <el-input
                style="width: 150px"
                v-model="formModel.socialCreditCode"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人" prop="responsible">
              <el-input
                style="width: 150px"
                v-model="formModel.responsible"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人电话" prop="phoneNumber">
              <el-input
                style="width: 150px"
                v-model="formModel.phoneNumber"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="资质文件" prop="fileUrls">
              <file-upload
                :isShowTip="false"
                v-model="formModel.fileUrls"
                :fileType="['png', 'jpg', 'jpeg']"
              ></file-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            :row="4"
            v-model="formModel.remark"
            style="width: 900px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-card>
      <el-card style="margin-bottom: 10px; padding: 0 70px" v-if="formModel.id">
        <el-descriptions title="">
          <el-descriptions-item label="id" span="1">{{
            formModel.id
          }}</el-descriptions-item>
          <el-descriptions-item label="最后编辑时间" span="2">{{
            formModel.updateTime
          }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-form>

    <SelectNameDialog
      :dialogVisible="dialogVisible"
      :userType="formModel.userType"
      :userInfoId="formModel.userInfoId"
      @onClose="dialogVisible = false"
      @onSubmit="handleOnSubmit"
    ></SelectNameDialog>

    <!-- 供应商子账号弹窗 -->
    <el-dialog
      :title="subAccountTitle"
      :visible.sync="subAccountVisible"
      :before-close="handleSubClose"
    >
      <el-form :model="subFormModel" label-width="100px">
        <el-form-item label="姓名">
          <el-input placeholder="请输入" v-model="subFormModel.name"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input
            placeholder="请输入"
            v-model="subFormModel.userName"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            placeholder="请输入"
            v-model="subFormModel.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="账号状态">
          <el-switch
            v-model="subFormModel.status"
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="subAccountVisible = false">取 消</el-button>
        <el-button type="primary" @click="subAccountVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { userTypeList } from "@/configEnum";
import SelectNameDialog from "@/components/SelectDialog/SelectNameDialog";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "@/api/system/menu";
import {
  listRole,
  deptTreeSelect,
  getRole,
  dataScope,
  changeRoleStatus,
} from "@/api/system/role";
import { listDept, listDeptChildren } from "@/api/system/dept";
import {
  addOrders,
  getOrders,
  updateOrders,
} from "@/api/service/purchase/supplier.js";
import { validatePhoneNumber } from "@/utils";
export default {
  components: {
    SelectNameDialog,
  },
  data() {
    return {
      originName: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限",
        },
        {
          value: "2",
          label: "自定数据权限",
        },
        {
          value: "3",
          label: "本部门数据权限",
        },
        {
          value: "4",
          label: "本部门及以下数据权限",
        },
        {
          value: "5",
          label: "仅本人数据权限",
        },
      ],
      deptOptions: [],
      // 菜单列表
      menuOptions: [],
      rules: {
        name: [
          {
            required: true,
            message: "请输入供应商名称",
            trigger: "change",
          },
        ],
        abName: [
          {
            required: true,
            message: "请输入供应商简称",
            trigger: "change",
          },
        ],
        socialCreditCode: [
          {
            required: true,
            message: "请输入统一社会信用代码",
            trigger: "change",
          },
        ],
        responsible: [
          {
            required: true,
            message: "请输入负责人",
            trigger: "change",
          },
        ],
        phoneNumber: validatePhoneNumber(),
        fileUrls: [
          {
            required: true,
            message: "请上传资质文件",
            trigger: "change",
          },
        ],
      },
      subAccountTitle: "新增子账号",
      subFormModel: {
        name: undefined,
        userName: undefined,
        phone: undefined,
        status: true,
      },
      subAccountVisible: false,
      subAccountList: [],
      userTypeList,
      formModel: {
        name: undefined,
        abName: undefined,
        socialCreditCode: undefined,
        responsible: undefined,
        phoneNumber: undefined,
        fileUrls: undefined,
      },
      dialogVisible: false,
      roleList: [], // 角色列表
      orgList: [], // 机构列表
      deptList: [], // 部门列表
      deptExpand: true,
      deptNodeAll: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectId: null,
      },
    };
  },
  watch: {
    userType(n, o) {},
  },
  methods: {
    handleCardChange(val) {
      this.originName = "";
    },
    // 选择姓名弹框确认
    handleOnSubmit(userInfoId, name) {
      console.log(name);
      this.originName = name;
      this.formModel = { ...this.formModel, userInfoId };
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.handleValidateSuccess();
        } else {
          return false;
        }
      });
    },
    handleValidateSuccess() {
      if (!this.userId) {
        addOrders({
          ...this.formModel,
        }).then((res) => {
          console.log(res);
          this.handleOkToLink();
        });
      } else {
        updateOrders({
          ...this.formModel,
        }).then((res) => {
          console.log(res);
          this.handleOkToLink();
        });
      }
    },
    handleOkToLink() {
      this.$modal.msgSuccess("操作成功");
      // this.getUserInfo(this.userId);
      this.$router.push({
        path: "/purchase/supplier/index",
      });
    },
    handleOrg() {
      // 获取部门列表
      listDeptChildren({
        orgId: this.formModel.orgId,
      }).then((res) => {
        console.log(res);
        this.deptList = res.data;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then((response) => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    handleBack() {
      this.$router.push({
        path: "/purchase/supplier/index",
      });
    },
    removeSubAccount(row) {
      this.$confirm("确定要删除此账号吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    updateSubAccount(row) {
      this.subAccountVisible = true;
      this.subAccountTitle = "修改子账号";
      this.subFormModel = {
        ...this.subFormModel,
        ...row,
      };
    },
    addSubAccount() {
      this.subAccountVisible = true;
    },
    handleSubClose() {},
    handleSelectName() {
      this.dialogVisible = true;
    },
    getRoleList() {
      /** 查询角色列表 */
      this.loading = true;
      listRole({
        pageNum: 1,
        pageSize: 10000,
      }).then((response) => {
        this.roleList = response.rows;
      });
    },
    /** 查询机构列表 */
    getOrgList() {
      listDept({
        orgType: 1,
      }).then((response) => {
        this.orgList = this.handleTree(response.data, "orgId");
        console.log(this.orgList);
      });
    },
    getUserInfo(userId) {
      if (userId) {
        getOrders(userId).then((response) => {
          console.log("11123", response);
          this.formModel = {
            ...this.formModel,
            ...response.data,
            ...response.sysUserInfo,
          };
        });
      }
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == "dept") {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    /** 分配数据权限操作 */
    handleDataScope(roleId) {
      const deptTreeSelect = this.getDeptTree(roleId);
      getRole(roleId).then((response) => {
        this.$nextTick(() => {
          deptTreeSelect.then((res) => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
      });
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
  },
  created() {
    this.getDeptTree(1);
    this.getMenuTreeselect();
    // 获取机构列表
    this.getOrgList();
    // 获取角色列表
    this.getRoleList();
    this.userId = this.$route.query.id;
    if (this.userId) {
      this.getUserInfo(this.userId);
    }
  },
  computed: {
    title() {
      return !this.$route?.query?.id ? "新增供应商" : "修改供应商";
    },
  },
};
</script>

<style lang="scss" scoped>
.tree-border {
  width: 200px;
}
</style>
